package com.zhao.shiyuanbaoyou.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhao.shiyuanbaoyou.R;
import com.zhao.shiyuanbaoyou.urlutil.Constant;
import com.zhao.shiyuanbaoyou.adapter.HomeAdapter;
import com.zhao.shiyuanbaoyou.bean.HomeBean;
import com.zhao.shiyuanbaoyou.bean.NewsBean;
import com.zhao.shiyuanbaoyou.bean.ViewPagerBean;
import com.zhao.shiyuanbaoyou.helper.GlideImageLoader;
import com.zhao.shiyuanbaoyou.interfacepackage.IViewPager;
import com.zhao.shiyuanbaoyou.util.OkHttpUtil;
import com.zhao.shiyuanbaoyou.util.SpacesItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by 张昭 on 2016/11/11.
 */

public class HomeFragment extends Fragment {
    private Context mContext;
    private Banner fragmentBanner;
    private ImageView imageView_news, imageView_phone, imageView_meizhuang, imageView_food, imageView_fanally;
    private RecyclerView recyclerView_main;
    private List<String> mUrlImage = new ArrayList<>();
    private List<ViewPagerBean.AdListBean> mlist = new ArrayList<>();
    private List<HomeBean.RowsBean> mlist_home = new ArrayList<>();
    private HomeAdapter adapter;
    private HomeBean homeBean;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        fragmentBanner = (Banner) view.findViewById(R.id.banner_fragment_home);
        recyclerView_main = (RecyclerView) view.findViewById(R.id.recyclerView_fragment);
        imageView_news = (ImageView) view.findViewById(R.id.imageView_fragment_news);
        imageView_phone = (ImageView) view.findViewById(R.id.imageView_fragment_phone);
        imageView_meizhuang = (ImageView) view.findViewById(R.id.imageView_fragment_meizhuang);
        imageView_food = (ImageView) view.findViewById(R.id.imageView_fragment_food);
        imageView_fanally = (ImageView) view.findViewById(R.id.imageView_fragment_fianlly);
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initGetLunBoJson();
        initGetNewsJson();
        initGetHomeJson();

    }

    private void initGetHomeJson() {
//new Thread(new Runnable() {
//    @Override
//    public void run() {
//        try {
//            String json= OkHttpUtil.run(Constant.Homefragment_URL);
//            Log.i("TAG", "--------->>>>run: " + json.toString());
//            homeBean=adapter.parseJsonToBean(json);
//            mlist_home=homeBean.getRows();
//            Log.i("TAG", "--------->>>>run: " + mlist_home);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//});
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.Home_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IViewPager iViewPager = retrofit.create(IViewPager.class);
        Call<HomeBean> call=iViewPager.getJsonHomeString();
        call.enqueue(new Callback<HomeBean>() {
            @Override
            public void onResponse(Call<HomeBean> call, Response<HomeBean> response) {
                if (response.isSuccessful()){
                    mlist_home=response.body().getRows();
                    recyclerView_main.setLayoutManager(new GridLayoutManager(mContext, 2));
                    recyclerView_main.setHasFixedSize(true);
                    recyclerView_main.addItemDecoration(new SpacesItemDecoration(3));
                    adapter = new HomeAdapter(mContext, mlist_home);
                    recyclerView_main.setAdapter(adapter);
                    Log.i("TAG", "------->>>>onResponse: "+mlist_home.get(1).getName());
                }
            }

            @Override
            public void onFailure(Call<HomeBean> call, Throwable t) {

            }
        });
    }
    private void initGetNewsJson() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.News_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        IViewPager iViewPager = retrofit.create(IViewPager.class);
        Observable<List<NewsBean>> observable = iViewPager.getJsonNewsString();
        //指定主线程
        observable.subscribeOn(Schedulers.io())
                //指定工作线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<NewsBean>>() {
                    @Override
                    public void call(List<NewsBean> newsBeen) {

                        Glide.with(mContext).load(newsBeen.get(0).getImgUrl()).into(imageView_news);
//                        Glide.with(mContext).load(newsBeen.get(1).getImgUrl()).into(imageView_phone);
//                        Glide.with(mContext).load(newsBeen.get(2).getImgUrl()).into(imageView_food);
//                        Glide.with(mContext).load(newsBeen.get(3).getImgUrl()).into(imageView_meizhuang);
//                        Glide.with(mContext).load(newsBeen.get(4).getImgUrl()).into(imageView_fanally);
                    }
                });
    }

    private void initGetLunBoJson() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        IViewPager iViewPager = retrofit.create(IViewPager.class);
        Observable<ViewPagerBean> observable = iViewPager.getJsonString();
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ViewPagerBean>() {
                    @Override
                    public void call(ViewPagerBean viewPagerBean) {
                        mlist = viewPagerBean.getAdList();
                        for (int i = 0; i < mlist.size(); i++) {
                            mUrlImage.add(mlist.get(i).getImgUrl());
                        }

                        fragmentBanner.setBannerStyle(BannerConfig.CENTER);
                        fragmentBanner.setImageLoader(new GlideImageLoader());
                        //设置图片集合
                        fragmentBanner.setImages(mUrlImage);
                        //设置自动轮播，默认为true
                        fragmentBanner.isAutoPlay(true);
                        //设置轮播时间
                        fragmentBanner.setDelayTime(1500);
                        //设置指示器位置（当banner模式中有指示器时）
                        fragmentBanner.setIndicatorGravity(BannerConfig.CENTER);
                        //设置RecyclerView的适配器以及样式
                        fragmentBanner.start();
                    }

                });

    }
}
